package library.controller;

import library.po.Book;
import library.po.Borrow;
import library.po.User;
import library.service.BookService;
import library.service.BookTypeService;
import library.service.impl.BookTypeServiceImpl;
import library.service.impl.BorrowServiceImpl;
import library.service.UserService;
import library.service.impl.BookServiceImpl;
import library.service.BorrowService;
import library.service.impl.UserServiceImpl;
import view.CURD.*;
import view.info.OverviewDialog;
import view.info.PersonalInfoDialog;
import view.login.LoginDialog;
import view.main.MainFrame;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.Date;

import static java.lang.System.out;


public class FrameListener implements ActionListener {
    private MainFrame owner;
    private JDialog dialog;
    private JPasswordField used,renew;
    private User toolUser,renewUser;
    private UserService userService = new UserServiceImpl();
    private BookService bookService = new BookServiceImpl();
    private BorrowService borrowService = new BorrowServiceImpl();
    private BookTypeService bookTypeService = new BookTypeServiceImpl();
    private PersonalInfoDialog pid;
    private OverviewDialog overviewDialog;
    private UserDialog userDialog;
    private SelectDialog selectDialog;
    private OverviewUserDialog overviewUserDialog;
    private BookViewDialog bookViewDialog;
    private BookDialog bookDialog;
    private Book book;
    private BorrowDialog borrowDialog;
    private BookTypeDialog bookTypeDialog;
    public FrameListener(MainFrame owner,User user){
        this.owner = owner;
        this.toolUser = user;
    }
    public FrameListener(JDialog dialog, JPasswordField used,JPasswordField renew){
        this.dialog = dialog;
        this.used = used;
        this.renew = renew;
    }
    public void setPasswordField(JPasswordField used,JPasswordField renew){
        this.used = used;
        this.renew = renew;
    }
    public void setOverviewDialog(OverviewDialog od){
        this.overviewDialog = od;
    }
    public void setDialog(JDialog dialog){
        this.dialog = dialog;
    }
    public BookService getBookService(){
        return this.bookService;
    }
    public FrameListener(){
        super();
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        /*开始菜单*/
        //退出
        if ("Exit".equals(e.getActionCommand())){
            owner.dispose();
            userService.closeSqlsession();
            bookService.closeSqlsession();
        }
        //重新登陆
        else if ("ReLogin".equals(e.getActionCommand())){
            owner.dispose();
            userService.closeSqlsession();
            bookService.closeSqlsession();
            new LoginDialog();
        }
        //修改密码
        else if ("UpdatePassword".equals(e.getActionCommand())){
            new UpdatePasswordDialog(owner);
        }
        else if ("PasswordUpdatePost".equals(e.getActionCommand())){
            if(this.checkPassword(used.getText().trim())&&used.getText().trim()!=renew.getText().trim()){
                toolUser.setUserPassword(renew.getText().trim());
                userService.updatePassword(toolUser);
                JOptionPane.showMessageDialog(dialog, "修改密码成功!","成功",JOptionPane.INFORMATION_MESSAGE);
                dialog.dispose();
            }
            else{
                JOptionPane.showMessageDialog(dialog, "请检查原密码是否正确，并且新密码不可与原密码相同。","修改密码失败",JOptionPane.ERROR_MESSAGE);
            }
        }
        else if ("PasswordCancel".equals(e.getActionCommand())){
            JOptionPane.showMessageDialog(dialog, "退出修改！","取消",JOptionPane.INFORMATION_MESSAGE);
            dialog.dispose();
        }
        //查看个人信息
        else if ("CheckPersonalInfo".equals(e.getActionCommand())){
            this.pid = new PersonalInfoDialog(owner,toolUser);
        }
        else if("InfoExit".equals(e.getActionCommand())){
            if (dialog!=null)
                dialog.dispose();
            else if (userDialog != null)
                userDialog.dispose();
            else if(pid!=null)
                pid.dispose();
        }
        //查看已借书籍
        else if("ViewBorrowBooks".equals(e.getActionCommand())){
            new OverviewDialog(pid,"已借图书记录",toolUser);
        }
        ///修改个人信息
        else if("UpdatePersonalInfo".equals(e.getActionCommand())){
            this.userDialog = new UserDialog(owner,"用户修改信息",toolUser);
        }
        else if ("userUpdatePost".equals(e.getActionCommand())){
            renewUser = this.userDialog.getUserInstance();
            if(renewUser != null) {
                userService.updateById(renewUser);
                JOptionPane.showMessageDialog(userDialog, "修改成功！请重新登录！");
                userDialog.dispose();
                owner.dispose();
                new LoginDialog();
            }else {
                JOptionPane.showMessageDialog(userDialog, "修改失败！请检查各项信息是否符合要求！");
            }
        }
        //复制信息
        else if("CopyInfo".equals(e.getActionCommand())) {
            if (overviewDialog!=null){
                int selRow = overviewDialog.getSelRow();
                if(selRow<0) {
                    JOptionPane.showMessageDialog(overviewDialog, "请选择一行数据");
                }else {
                    if ("已借图书记录".equals(overviewDialog.getTitle())) {
                        Borrow borrow = null;
                        if (borrowService.selectByUserId(toolUser.getUserId()).get(overviewDialog.getSelRow()) != null)
                            borrow = borrowService.selectByUserId(toolUser.getUserId()).get(overviewDialog.getSelRow());
                        StringSelection stsel = new StringSelection(borrow.toString());
                        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stsel, stsel);
                        JOptionPane.showMessageDialog(overviewDialog, "复制信息成功！");
                    } else if ("用户管理界面".equals((overviewDialog.getTitle()))) {
                        User user = null;
                        if (userService.selectAllUsers().get(overviewDialog.getSelRow()) != null)
                            user = userService.selectAllUsers().get(overviewDialog.getSelRow());
                        StringSelection stsel = new StringSelection(user.toString());
                        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stsel, stsel);
                        JOptionPane.showMessageDialog(overviewDialog, "复制信息成功！");
                    }
                }
            }
            else{
                int selRow = bookViewDialog.getSelRow();
                if (selRow<0){
                    JOptionPane.showMessageDialog(bookViewDialog, "请选择一行数据");
                }else {
                    Book book = null;
                    if (bookService.selectAllBooks().get(bookViewDialog.getSelRow()) != null)
                        book = bookService.selectAllBooks().get(bookViewDialog.getSelRow());
                    StringSelection stsel = new StringSelection(book.toString());
                    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stsel, stsel);
                    JOptionPane.showMessageDialog(bookViewDialog, "复制信息成功！");
                }
            }
        }
        //续借
        else if ("ReBorrow".equals(e.getActionCommand())){
            if(toolUser.getUserCredit()==1){
                int selRow = overviewDialog.getSelRow();
                if(selRow<0) {
                    JOptionPane.showMessageDialog(overviewDialog, "请选择一行数据");
                }else {
                    if (borrowService.selectByUserId(toolUser.getUserId()).get(overviewDialog.getSelRow()).getRenewTimes()>0){
                        int i = borrowService.renew(borrowService.selectByUserId(toolUser.getUserId()).get(overviewDialog.getSelRow()).getBorrowId());
                        overviewDialog.borrowRefresh(borrowService.selectByUserId(toolUser.getUserId()));
                        JOptionPane.showMessageDialog(overviewDialog, "续借成功");
                    }
                    else
                        JOptionPane.showMessageDialog(overviewDialog, "剩余续借次数不足！","续借失败",JOptionPane.ERROR_MESSAGE);
                }
            }
            else
                JOptionPane.showMessageDialog(overviewDialog, "您的信用太低！无法续借！请缴纳罚款后咨询系统管理员修改信息！","续借失败",JOptionPane.ERROR_MESSAGE);
        }
        //查询borrow
        else if ("SelectBorrowDialog".equals(e.getActionCommand())){
            selectDialog = new SelectDialog(overviewDialog,"查询借阅信息");
        }
        else if ("SelectBorrow".equals(e.getActionCommand())){
            if (!selectDialog.getTextField().getText().trim().equals("")&&selectDialog.getTextField().getText().trim()!=null) {
                overviewDialog.borrowRefresh(borrowService.selectBorrow(selectDialog.getTextField().getText().trim()));
                JOptionPane.showMessageDialog(selectDialog, "查询成功共查到"+borrowService.selectBorrow(selectDialog.getTextField().getText().trim()).size()+"条记录");
                selectDialog.dispose();
            }
            else{
                JOptionPane.showMessageDialog(selectDialog,"查询失败");
            }
        }
        //查询用户
        else if ("SelectUserDialog".equals(e.getActionCommand())){
            selectDialog = new SelectDialog(overviewUserDialog,"查询用户");
        }
        else if ("SelectUser".equals(e.getActionCommand())){
            if (!selectDialog.getTextField().getText().trim().equals("")&&selectDialog.getTextField().getText().trim()!=null) {
                JOptionPane.showMessageDialog(selectDialog, "查询成功共查到"+userService.selectUser(selectDialog.getTextField().getText().trim()).size()+"条记录");
                selectDialog.dispose();
                overviewUserDialog.userRefresh(userService.selectUser(selectDialog.getTextField().getText().trim()));
            }
            else{
                JOptionPane.showMessageDialog(selectDialog,"查询失败");
            }
        }
        //添加用户
        else if ("InsertUser".equals(e.getActionCommand())){
            new UserDialog(overviewUserDialog,"添加用户",null);
        }
        else if ("UserAddPost".equals(e.getActionCommand())){
            User user;
            user = getUserInstance();
            if(user != null) {
                userService.insert(user);
                JOptionPane.showMessageDialog(userDialog, "添加成功！");
                userDialog.dispose();
                overviewUserDialog.userRefresh(userService.selectAllUsers());
            }else {
                JOptionPane.showMessageDialog(userDialog, "添加失败！请确认信息！");
            }
        }
        //删除用户
        else if ("DeleteUser".equals(e.getActionCommand())){
            int selRow = overviewDialog.getSelRow();
            if (selRow>0){
                int i = userService.deleteById(userService.selectAllUsers().get(selRow).getUserId());
                JOptionPane.showMessageDialog(overviewDialog,i+"条数据删除成功！");
                overviewUserDialog.userRefresh(userService.selectAllUsers());
            }
            else {
                JOptionPane.showMessageDialog(userDialog,"请选择一行数据","删除失败！",JOptionPane.ERROR_MESSAGE);
            }
        }
        //修改用户
        else if("UpdateUserDialog".equals(e.getActionCommand())){
            int selRow = overviewDialog.getSelRow();
            if (selRow>-1)
                this.userDialog = new UserDialog(overviewUserDialog,"修改用户信息",userService.selectAllUsers().get(selRow));
            else {
                JOptionPane.showMessageDialog(userDialog,"请选择一行数据","修改失败！",JOptionPane.ERROR_MESSAGE);
            }
        }
        else if ("UpdateUser".equals(e.getActionCommand())){
            User user;
            user = userDialog.getUserInstance();
            int i = userService.updateById(user);
            if (i>0)
                JOptionPane.showMessageDialog(overviewDialog,i+"条数据修改成功！");
            else
                JOptionPane.showMessageDialog(overviewDialog,"修改失败");
            userDialog.dispose();
            overviewUserDialog.userRefresh(userService.selectAllUsers());
        }
        //用户管理
        else if ("OverviewUser".equals(e.getActionCommand())){
            overviewUserDialog = new OverviewUserDialog(owner, "用户管理界面");
        }
        //查询借阅日志信息
        else if ("OverViewBorrow".equals(e.getActionCommand())){
            overviewDialog = new OverviewDialog(owner,"借阅记录");
        }
        //总览图书
        else if ("AdminViewBook".equals(e.getActionCommand())){
            bookViewDialog = new BookViewDialog(owner,"图书管理",this.toolUser);
        }
        else if ("ReaderViewBooks".equals(e.getActionCommand())){
            bookViewDialog = new BookViewDialog(owner,"总览图书",this.toolUser);
        }
        //新增/更新图书信息
        else if ("InsertBookDialog".equals(e.getActionCommand())){
            bookDialog = new BookDialog(bookViewDialog,"添加图书",null);
        }
        else if ("UpdateBookDialog".equals(e.getActionCommand())){
            if (bookViewDialog.getTitle().equals("图书管理")){
                book = bookService.selectByIsbn(bookService.selectAllBooks().get(bookViewDialog.getSelRow()).getBookIsbn());
                bookDialog = new BookDialog(bookViewDialog,"修改图书信息",book);
            }
            else if (bookViewDialog.getTitle().equals("总览图书")){
                if(toolUser.getUserCredit()==1){
                    int selRow = bookViewDialog.getSelRow();
                    if (selRow>-1){
                        borrowDialog = new BorrowDialog(bookViewDialog,"借阅卡",bookService.selectByIsbn(bookService.selectAllBooks().get(bookViewDialog.getSelRow()).getBookIsbn()),toolUser);
                    }
                    else
                        JOptionPane.showMessageDialog(bookViewDialog,"请选择一行数据","借阅失败！",JOptionPane.ERROR_MESSAGE);
                }
                else
                    JOptionPane.showMessageDialog(bookViewDialog,"您的信用太低！无法借阅！请缴纳罚款后咨询系统管理员修改信息！","借阅失败！",JOptionPane.ERROR_MESSAGE);
            }

        }
        else if ("BookPost".equals(e.getActionCommand())){
            if ("添加图书".equals(bookDialog.getTitle())){
                int i = bookService.insert(bookDialog.getBookInstance());
                if (i>0){
                    JOptionPane.showMessageDialog(bookDialog,"添加图书成功！");
                    bookDialog.dispose();
                    bookViewDialog.bookRefresh(bookService.selectAllBooks());
                }
                else
                    JOptionPane.showMessageDialog(bookDialog,"添加失败!","ERROR",JOptionPane.ERROR_MESSAGE);
            }
            else if ("修改图书信息".equals(bookDialog.getTitle())){
                out.println(bookDialog.getBookInstance());
                int i = bookService.updateByIsbn(bookDialog.getBookInstance());
                if (i>0){
                    JOptionPane.showMessageDialog(bookDialog,"修改图书成功！");
                    bookDialog.dispose();
                    bookViewDialog.bookRefresh(bookService.selectAllBooks());
                }
                else
                    JOptionPane.showMessageDialog(bookDialog,"修改失败!","ERROR",JOptionPane.ERROR_MESSAGE);
            }
        }
        //删除图书
        else if ("DeleteBook".equals(e.getActionCommand())){
            int selRow = bookViewDialog.getSelRow();
            if (selRow>0){
                int i = bookService.deleteByIsbn(bookService.selectAllBooks().get(selRow).getBookIsbn());
                JOptionPane.showMessageDialog(bookViewDialog,i+"条数据删除成功！");
                bookViewDialog.bookRefresh(bookService.selectAllBooks());
            }
            else {
                JOptionPane.showMessageDialog(bookViewDialog,"请选择一行数据","删除失败！",JOptionPane.ERROR_MESSAGE);
            }
        }
        //查询图书
        else if ("SelectBookDialog".equals(e.getActionCommand())){
            selectDialog = new SelectDialog(bookViewDialog,"查询图书");
        }
        else if ("SelectBook".equals(e.getActionCommand())){
            if (!selectDialog.getTextField().getText().trim().equals("")&&selectDialog.getTextField().getText().trim()!=null) {
                bookViewDialog.bookRefresh(bookService.selectBook(selectDialog.getTextField().getText().trim()));
                JOptionPane.showMessageDialog(selectDialog, "查询成功!共查到"+bookService.selectBook(selectDialog.getTextField().getText().trim()).size()+"条记录");
                selectDialog.dispose();
            }
            else{
                JOptionPane.showMessageDialog(selectDialog,"查询失败");
            }
        }
        //借阅图书
        else if ("InsertBorrow".equals(e.getActionCommand())){
            Borrow borrow = new Borrow();
            borrow.setBorrowState("借阅中");
            borrow.setBorrowTime(new Date());
            borrow.setBookIsbn(borrowDialog.getBook().getBookIsbn());
            borrow.setBookName(borrowDialog.getBook().getBookName());
            borrow.setUserId(toolUser.getUserId());
            borrow.setRenewTimes(2);
            if (borrowDialog.getBook().getBookReserve()>0){
                int i = borrowService.insert(borrow);
                int j = bookService.borrowBook(borrowDialog.getBook().getBookIsbn());
                if (i>0&&j>0){
                    JOptionPane.showMessageDialog(borrowDialog, "借阅成功!");
                    borrowDialog.dispose();
                    bookViewDialog.bookRefresh(bookService.selectAllBooks());
                }
                else
                    JOptionPane.showMessageDialog(borrowDialog,"查询失败","ERROR",JOptionPane.ERROR_MESSAGE);
            }
            else
                JOptionPane.showMessageDialog(borrowDialog,"该书库存不足！","ERROR",JOptionPane.ERROR_MESSAGE);
        }
        //归还书籍
        else if ("ReturnBook".equals(e.getActionCommand())){
            int selRow = overviewDialog.getSelRow();
            if (selRow>-1){
                if (borrowService.selectByUserId(toolUser.getUserId()).get(selRow).getBorrowState().equals("借阅中")){
                    Borrow borrow = new Borrow();
                    borrow.setBorrowState("已归还");
                    borrow.setReturnTime(new Date());
                    borrow.setBorrowId(borrowService.selectByUserId(toolUser.getUserId()).get(selRow).getBorrowId());
                    borrow.setRenewTimes(0);
                    int i = borrowService.returnBook(borrow);
                    i = bookService.returnBook(borrowService.selectByUserId(toolUser.getUserId()).get(selRow).getBookIsbn());
                    overviewDialog.borrowRefresh(borrowService.selectByUserId(toolUser.getUserId()));
                    JOptionPane.showMessageDialog(overviewDialog,"还书成功！","success",JOptionPane.INFORMATION_MESSAGE);
                }
                else
                    JOptionPane.showMessageDialog(overviewDialog,"该书已经归还！","还书失败！",JOptionPane.ERROR_MESSAGE);
            }
            else
                JOptionPane.showMessageDialog(overviewDialog,"请选择一行数据","还书失败！",JOptionPane.ERROR_MESSAGE);
        }
        //导出Excel
        else if ("Output".equals(e.getActionCommand())) {
            // TODO add your handling code here:导出
            if (overviewDialog != null) {
                if (overviewDialog.getTitle().equals("借阅记录")) {
                    FileDialog fd = new FileDialog(owner, "保存借阅信息", FileDialog.SAVE);
                    fd.setLocation(500, 350);
                    fd.setVisible(true);
                    String stringfile = fd.getDirectory() + fd.getFile() + ".xls";
                    try {
                        ExcelExporter export = new ExcelExporter();
                        export.exportTable(overviewDialog.getAdminBorrowTable(borrowService.selectAllBorrow()), new File(stringfile));
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            } else if (bookViewDialog != null) {
                if (bookViewDialog.getTitle().equals("图书管理") || bookViewDialog.getTitle().equals("总览图书")) {
                    FileDialog fd = new FileDialog(bookViewDialog, "保存图书信息", FileDialog.SAVE);
                    fd.setLocation(500, 350);
                    fd.setVisible(true);
                    String stringfile = fd.getDirectory() + fd.getFile() + ".xls";
                    try {
                        ExcelExporter export = new ExcelExporter();
                        export.exportTable(bookViewDialog.getBookTable(bookService.selectAllBooks()), new File(stringfile));
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
        else if ("OutputUser".equals(e.getActionCommand())){
            FileDialog fd = new FileDialog(overviewUserDialog, "保存用户信息", FileDialog.SAVE);
            fd.setLocation(500, 350);
            fd.setVisible(true);
            String stringfile = fd.getDirectory() + fd.getFile() + ".xls";
            try {
                ExcelExporter export = new ExcelExporter();
                export.exportTable(overviewUserDialog.getUserTable(userService.selectAllUsers()), new File(stringfile));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        else if ("AddBookType".equals(e.getActionCommand())){
            bookTypeDialog = new BookTypeDialog(owner);
        }
        else if ("AddBookTypePost".equals(e.getActionCommand())){
            if (bookTypeDialog.getBookType()!=null){
                bookTypeService.insert(bookTypeDialog.getBookType());
                JOptionPane.showMessageDialog(overviewDialog,"添加成功！");
                bookTypeDialog.dispose();
            }
            else
                JOptionPane.showMessageDialog(overviewDialog,"无法添加！","添加失败！",JOptionPane.ERROR_MESSAGE);
        }
    }
    public boolean checkPassword(String password){
        if (password.equals(toolUser.getUserPassword())){return true;}
        else {return false;}
    }
    public void setUserDialog(UserDialog ud){
        this.userDialog = ud;
    }
    public String typeToIdentity(int type) {
        String str = null;
        if (type == 1) {
            str = "借阅者";
        }
        else if(type == 3){
            str = "图书管理员&借阅者";
        }
        else if(type == 2){
            str = "系统管理员&借阅者";
        }
        else if (type == 4)
            str = "系统管理员&图书管理员&借阅者";
        return str;
    }
    public void setUserAddDialog(UserDialog userAddDialog) {
        userDialog = userAddDialog;
    }
    public User getUserInstance() {
        String userId = null;
        String userName = null;
        String password = null;
        String sex = null;
        Integer type = 0;
        Integer credit = 100;
        User user = null;
        /*获取账号*/
        String userIdInput  = userDialog.getUserIdTextField().getText().trim();
        if(userIdInput != null && !"".equals(userIdInput) && !"用户名由20位以下字母和数字组成".equals(userIdInput)) {
            userId = userIdInput;
        }else {
            JOptionPane.showMessageDialog(userDialog, "用户名不能为空","输入错误",JOptionPane.ERROR_MESSAGE);
        }
        /*获取姓名*/
        String nameInput = userDialog.getUserNameTextField().getText().trim();
        if(nameInput != null && !"".equals(nameInput) && !"您的姓名".equals(nameInput)) {
            userName = nameInput;
        }else {
            JOptionPane.showMessageDialog(userDialog, "姓名不能为空","输入错误",JOptionPane.ERROR_MESSAGE);
        }
        /*获取密码*/
        String passwordInput = userDialog.getPasswordField().getText().trim();
        if(passwordInput != null && !"".equals(passwordInput)) {
            password = passwordInput;
        }
        else {
            JOptionPane.showMessageDialog(userDialog, "密码不能为空","输入错误",JOptionPane.ERROR_MESSAGE);
        }
        /*获取性别*/
        String sexInput = userDialog.getSexBox().getSelectedItem().toString();
        if(sexInput != null && !"".equals(sexInput)&& !sexInput.equals("--请选择--")) {
            sex = sexInput;
        }
        else
            JOptionPane.showMessageDialog(userDialog, "请选择您的性别","输入错误",JOptionPane.ERROR_MESSAGE);
        /*获取身份*/
        out.println(userDialog.getTypeBox().getSelectedItem().toString());
        Integer typeInput = identityToType(userDialog.getTypeBox().getSelectedItem().toString());
        if(typeInput != null && !"".equals(typeInput)) {
            type = typeInput;
            out.println(userId);
            out.println(password);
            out.println(userName);
            out.println(sex);
            out.println(type);
        }else {
            JOptionPane.showMessageDialog(userDialog, "身份不能为空","输入错误",JOptionPane.ERROR_MESSAGE);
        }
        if(userId != null && userName != null && sex != null && type > 0 && password!=null) {
            user = new User(userId,password,userName,sex,type,credit);
        }
        out.println(user);
        return user;
    }
    //导出事件
    private void jButtonActionPerformed(java.awt.event.ActionEvent evt) {

    }
    public Integer identityToType(String identity){
        Integer type = 0;
        if (identity.equals("借阅者")){type = 1;}
        if (identity.equals("系统管理员&借阅者")){type = 2;}
        if (identity.equals("图书管理员&借阅者")){type = 3;}
        if (identity.equals("系统管理员&图书管理员&借阅者")){type = 4;}
        return type;
    }
}
